import getUserTempId from "@/utils/userTempId"
import { reqLogin,reqUserInfo,reqLogout } from "@/api";
const state = {
    userTempId: getUserTempId(),
    token: localStorage.getItem("token") || "",
    userInfo: {
        nickName: ""
    }
}
const mutations = {
    SET_TOKEN_STATE(state, payload) {
        state.token = payload.token
    },
    SET_USERINFO_STATE(state, payload) {
        state.userInfo = payload.userInfo
    },
    RESET_USERINFO_STATE(state) {
        state.token = ""
        state.userInfo = { nickName: "" }
        localStorage.removeItem("token")
    }
}
const actions={
    async getToken({commit},userInfo){
        try {
            const result = await reqLogin(userInfo)
            // 储存token
            localStorage.setItem("token", result.token);
            commit("SET_TOKEN_STATE",{token:result.token})
        }catch(e){
            return Promise.reject(e);
        }
    },
    // 获取用户信息
    async getUserInfo({commit}){
        try {
            const result = await reqUserInfo()
            commit("SET_USERINFO_STATE",{userInfo:result})
        }catch(e){
            return Promise.reject(e.message);
        }
    },
    getResetUser({commit}){
        commit("RESET_USERINFO_STATE")
    },
    // 退出登陆
    async getLogout({commit}){
        try{
            await reqLogout()
            // 成功后清空用户信息
            commit("RESET_USERINFO_STATE")
        }catch(e){
            return Promise.reject(e)
        }
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}